<template>
  <view class="container">
    <view class="tab-list">
      <view
        v-for="(item, index) in tabs"
        :key="index"
        class="tab-item"
        @click="tabclick(index, item.id)"
      >
        <text
          class="item-text"
          :class="[currentIndex == index ? 'atctive-color' : 'nomal-color']"
          >{{ item.name }}</text
        >
      </view>
    </view>
    <projet-list :list="proects" @loves="loves"></projet-list>
  </view>
</template>

<script>
import { uncollected, collectArciles, trees, projects } from "@/api/api.js";
export default {
  data() {
    return {
      tabs: [],
      currentIndex: 0,
      index: 1,
      cid: "",
      proects: [],
      total: 0,
    };
  },
  onLoad() {
    this.fetTabs();
  },
  onPullDownRefresh() {
    this.index = 1;
    this.proects = [];
    this.fetchProjects();
    uni.stopPullDownRefresh();
  },
  onReachBottom() {
    if (this.proects.length > this.total) {
      return;
    }
    this.index++;
    this.fetchProjects();
  },
  methods: {
    loves(index, id) {
      let isCollect = this.proects[index].collect;
      this.$set(this.proects[index], "collect", !isCollect);
      if (isCollect) {
        //取消收藏
        this.cancleCollects(id);
      } else {
        //添加收藏
        this.addCollects(id, this.proects[index]);
      }
    },
    async cancleCollects(id) {
      let rs = await uncollected(id);
      if (rs.errorCode == 0) {
        uni.showToast({
          title: "取消收藏",
          icon: "none",
        });
      }
    },
    async addCollects(id) {
      let rs = await collectArciles(id);

      if (rs.errorCode == 0) {
        uni.showToast({
          title: "收藏成功",
          icon: "none",
        });
      }
    },
    async fetchProjects() {
      let rs = await projects(this.index, this.cid);

      console.log("rs", rs);
      this.total = rs.data.total;

      this.proects = this.proects.concat(rs.data.datas);
    },
    async fetTabs() {
      let rs = await trees();
      this.tabs = rs.data;
      this.cid = this.tabs[0].id;
      this.fetchProjects();
    },
    //1/json?cid=294
    tabclick(index, id) {
      this.currentIndex = index;
      this.cid = id;
      this.proects = [];
      this.index = 1;
      this.fetchProjects();
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  .tab-list {
    display: flex;
    overflow: auto;

    .tab-item {
      .item-text {
        &:nth-child(1) {
          margin-left: 32rpx;
        }

        width: max-content;
        display: block;
        margin-right: 18rpx;
        height: 40rpx;

        &.atctive-color {
          color: red;
          font-family: 500;
          border-bottom: 1px solid green;
        }

        &.nomal-color {
          color: black;
        }
      }
    }
  }
}
</style>
